package com.hyb.algorithm.data.struct.str;

/**
 * @author: ybhu
 * @create: 2021/09/25 18:10
 * <p>
 * 14. 最长公共前缀
 * https://leetcode-cn.com/problems/longest-common-prefix/
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flow","flight"};

        LongestCommonPrefix exe = new LongestCommonPrefix();
        String ret = exe.longestCommonPrefix(strs);
        System.out.println(ret);
    }

    public String longestCommonPrefix(String[] strs) {

        int n=strs.length;

        String first=strs[0];
        int index=first.length();
        for(int i=1;i<n;i++){
            int ret=findCommonPrefix(first,strs[i]);
            index=Math.min(index,ret);

            if(index==0){
                return "";
            }
        }

        return first.substring(0,index);

    }

    private int findCommonPrefix(String str1,String str2){
        int n=str1.length();
        int m=str2.length();

        int index=0;
        while(index<n&&index<m){
            if(str1.charAt(index)==str2.charAt(index)){
                index++;
                continue;
            }
            break;
        }

        return index;
    }


}
